<?php

class PostController extends Controller {

    public function filters() {
	return array(
	    'accessControl'    // required to enable accessRules
	);
    }

    public function accessRules() {
	return array(
	    array('allow', // allow all users to perform 'index' and 'view' actions
		'actions' => array('view', 'search'),
		'users' => array('*'),
	    ),
	    array('allow',
		'actions' => array(
		    'list_post', 'my_post', 'delete', 'update', 'delete_file', 'reportabuse'
		),
		'users' => array('@')
	    ),
	    array('deny', // deny everybody else
		'users' => array('*')
	    )
	);
    }

    /*
     * list post in dashboard or my post
     */

    public function actionList_post($type = "") {
	/*
	 * post
	 */
	$model = new Posts();
	$model->is_private = Posts::IS_PUBLIC;
	if (isset($_POST['ajax']) && $_POST['ajax'] === 'post-form') {
	    echo CActiveForm::validate($model);
	    Yii::app()->end();
	}


	$error = array();
	if (isset($_POST['posting'])) {
	    //get capacity of files that user uploaded
	    $sizeUploadedOfUser = user()->getModel()->uploaded_size;
	    //get limit of file uploaded 
	    $limitSize = intval(settings()->get('site', 'size_upload_limit'));
	    $convertMb = number_format(floatval($limitSize / (1024 * 1024)), 2, '.', '');

	    $uploadedSize = 0;
	    $totalSize = 0;
	    $model->attributes = $_POST['Posts'];
	    $model->user_id = user()->id;

	    $aNamePhoto = array();
	    $audio = '';
	    $video = array(
		'upload' => '',
		'iframe' => ''
	    );

	    //$model->time_created = date('Y-m-d', time());

	    if ($model->validate()) {

		if (isset($_FILES['photo']['name']) && $_FILES['photo']['name'][0]) {
		    //check size of file uploaded
		    foreach ($_FILES['photo']['size'] as $size) {
			$totalSize += $size;
		    }

		    //if size of uploading file still hasn't been over limit size.
		    if (($totalSize + $sizeUploadedOfUser) < $limitSize) {
			//if user upload photo				

			for ($i = 0; $i < count($_FILES['photo']['name']); $i++) {
			    if ($_FILES['photo']['name'][$i]) {
				$fileSize = $_FILES['photo']['size'][$i];
				$aImg = uploadImg(UPLOAD_PATH . 'photo/', $_FILES['photo']['tmp_name'][$i], $_FILES['photo']['name'][$i]);
				if (isset($aImg['success'])) {
				    $aNamePhoto[] = $aImg['name'];
				    $uploadedSize += $fileSize;
				}
			    }
			}
		    } else {
			$error[] = 'You have uploaded over ' . $convertMb . 'Mb';
		    }
		}




		//upload audio
		if ((isset($_FILES['audio']['name']) && $_FILES['audio']['name'])) {
		    if (($_FILES['audio']['size'] + $sizeUploadedOfUser) < $limitSize) {
			$fileSize = $_FILES['audio']['size'];
			$aAudio = uploadAudio(UPLOAD_PATH . 'audio/', $_FILES['audio']['tmp_name'], $_FILES['audio']['name']);
			if (isset($aAudio['success'])) {
			    $audio = $aAudio['name'];
			    $uploadedSize += $fileSize;
			}
		    } else {
			$error[] = 'You have uploaded over ' . $convertMb . 'Mb';
		    }
		}

		//upload video
		if ((isset($_FILES['video']['name']) && $_FILES['video']['name'])) {

		    if (($_FILES['video']['size'] + $sizeUploadedOfUser) < $limitSize) {
			//||(isset($_POST['iframe']) && $_POST['iframe'])) {		
			$fileSize = $_FILES['video']['size'];
			$aVideo = uploadVideo(UPLOAD_PATH . 'video/', $_FILES['video']['tmp_name'], $_FILES['video']['name'], $fileSize, settings()->get('site', 'size_video_upload_limit'));
			if (isset($aVideo['success'])) {
			    $video['upload'] = $aVideo['name'];
			    $uploadedSize += $fileSize;
			} else {
			    $error[] = $aVideo['message'];
			}
//		    if ($_POST['iframe']) {
//			$video['iframe'] = $_POST['iframe'];
//		    }			
		    } else {
			$error[] = 'You have uploaded over ' . $convertMb . 'Mb';
		    }
		}

		if (!$error) {
		    user()->getModel()->uploaded_size = $sizeUploadedOfUser + $uploadedSize;
		    user()->getModel()->save();
		    $aAttachment = array(
			'photo' => $aNamePhoto,
			'audio' => $audio,
			'video' => $video
		    );
		    $model->attachment = serialize($aAttachment);
		    $model->save();
		} else {
		    //when there was error
		    //delete all file were uploaded
		    if ($aNamePhoto) {
			foreach ($aNamePhoto as $photo) {
			    deleteFile(UPLOAD_PATH . 'photo/' . $photo);
			}
		    }
		    if ($audio) {
			deleteFile(UPLOAD_PATH . 'audio/' . $audio);
		    }
		    if ($video) {
			deleteFile(UPLOAD_PATH . 'video/' . $video['upload']);
		    }
		}
		$model->title = '';
		$model->content = '';
		$model->tags = '';
	    }
	}

	//get post 
	$critical = new CDbCriteria();
	//connenct categories table based on relationship method
	$critical->with = array('user');

	//get all friend 
	$aIdsFriend = Friend::getIdsFriend(user()->id);
	$sIdUser = user()->id;
//	if ($aIdsFriend) {
//	    foreach ($aIdsFriend as $id) {
//		$sIdUser .= ',' . $id;
//	    }
//	}
	$critical->addCondition('t.user_id IN(' . $sIdUser . ') ');

	$critical->order = 'post_id DESC';
	$iTotalRecord = $model->count($critical);

	$pages = new CPagination($iTotalRecord);
	$pages->pageSize = Posts::TOTAL_RECORD;
	$pages->applyLimit($critical);

	$this->render('list_post', array(
	    'model' => $model,
	    'aPosts' => $model->findAll($critical),
	    'pages' => $pages,
	    'iTotalRecord' => $iTotalRecord,
	    'error' => $error
	));
    }

    /**
     * 
     */
    public function actionView($id) {
	$model = $this->_loadModel($id);
	$totalComment = 0;
	$modelComment = array();
	if ($model) {
	    $modelComment = array();
	    //get total comment
	    $totalComment = Comment::getToltal($id);

	    if ($totalComment > 0) {
		//get comment of post
		$modelComment = Comment::model()->with('user')->findAll(array(
		    'condition' => 't.post_id=' . $id,
		    'order' => 't.comment_id DESC',
		    'limit' => Comment::TOTAL_RECORD
		));
	    }
	}
	$this->render('view', array(
	    'model' => $model,
	    'totalComment' => $totalComment,
	    'modelComment' => $modelComment
	));
    }

    /**
     * show my post
     */
    public function actionMy_post() {
	$model = new Posts('search');
	$model->unsetAttributes();  // clear any default values

	if (isset($_GET['Posts'])) {
	    $model->attributes = $_GET['Posts'];
	}
	$this->render('my-post', array(
	    'model' => $model
	));
    }

    /*
     * 
     */

    public function actionDelete($id) {

	$model = $this->_loadModel($id);
	if ($model->user_id == user()->id) {
	    $model->delete();
	} else {
	    throw CHttpException(404, "This post is not possession of you");
	}
    }

    /*
     * update post
     */

    public function actionUpdate($id) {
	$model = Posts::model()->findByPk($id);

	$notOwn = 0;
	$error = array();
	$attachment = unserialize($model->attachment);

	if ($model->user_id == user()->id) {

	    if (isset($_POST['posting'])) {
		//get capacity of files that user uploaded
		$sizeUploadedOfUser = user()->getModel()->uploaded_size;
		//get limit of file uploaded 
		$limitSize = intval(settings()->get('site', 'size_upload_limit'));
		$convertMb = number_format(floatval($limitSize / (1024 * 1024)), 2, '.', '');

		$uploadedSize = 0;
		$totalSize = 0;
		$model->attributes = $_POST['Posts'];
		$model->user_id = user()->id;
		//$model->time_created = date('Y-m-d', time());

		if ($model->validate()) {
		    /**
		     * get all size of file upload
		     */
		    if (isset($_FILES['photo']['name']) && $_FILES['photo']['name'][0]) {
			foreach ($_FILES['photo']['size'] as $size) {
			    $totalSize += $size;
			}
		    }
		    if ((isset($_FILES['audio']['name']) && $_FILES['audio']['name'])) {
			$totalSize += $_FILES['audio']['size'];
		    }
		    if ((isset($_FILES['video']['name']) && $_FILES['video']['name'])) {
			$totalSize += $_FILES['video']['size'];
		    }


		    if (($totalSize + $sizeUploadedOfUser) < $limitSize) {
			if (isset($_FILES['photo']['name']) && $_FILES['photo']['name'][0]) {

			    //check size of file uploaded
//			foreach ($_FILES['photo']['size'] as $size) {
//			    $totalSize += $size;
//			}
			    //if size of uploading file still hasn't been over limit size.
//			if (($totalSize + $sizeUploadedOfUser) < $limitSize) {
			    //if user upload photo							    
			    for ($i = 0; $i < count($_FILES['photo']['name']); $i++) {
				if ($_FILES['photo']['name'][$i]) {
//				    $fileSize = $_FILES['photo']['size'][$i];
				    $aImg = uploadImg(UPLOAD_PATH . 'photo/', $_FILES['photo']['tmp_name'][$i], $_FILES['photo']['name'][$i]);
				    if (isset($aImg['success'])) {
					//push to old array photo
					array_push($attachment['photo'], $aImg['name']);
					$aNamePhoto[] = $aImg['name'];
//					$uploadedSize += $fileSize;
				    }
				}
			    }
//			} else {
//			    $error[] = 'You have uploaded over ' . $convertMb . 'Mb';
//			}
			}




			//upload audio
			if ((isset($_FILES['audio']['name']) && $_FILES['audio']['name'])) {
//			if (($_FILES['audio']['size'] + $sizeUploadedOfUser) < $limitSize) {
//			    $fileSize = $_FILES['audio']['size'];
			    $aAudio = uploadAudio(UPLOAD_PATH . 'audio/', $_FILES['audio']['tmp_name'], $_FILES['audio']['name']);
			    if (isset($aAudio['success'])) {
				$attachment['audio'] = $aAudio['name'];
				$audio = $aAudio['name'];
//				$uploadedSize += $fileSize;
			    }
//			} else {
//			    $error[] = 'You have uploaded over ' . $convertMb . 'Mb';
//			}
			}

			//upload video
			if ((isset($_FILES['video']['name']) && $_FILES['video']['name'])) {

//			if (($_FILES['video']['size'] + $sizeUploadedOfUser) < $limitSize) {
			    //||(isset($_POST['iframe']) && $_POST['iframe'])) {
			    $fileSize = $_FILES['video']['size'];
			    $aVideo = uploadVideo(UPLOAD_PATH . 'video/', $_FILES['video']['tmp_name'], $_FILES['video']['name'], $fileSize, settings()->get('site', 'size_video_upload_limit'));
			    if (isset($aVideo['success'])) {
				$attachment['video']['upload'] = $aVideo['name'];
				$video['upload'] = $aVideo['name'];
//				$uploadedSize += $fileSize;
			    } else {
				$error[] = $aVideo['message'];
			    }
//		    if ($_POST['iframe']) {
//			$video['iframe'] = $_POST['iframe'];
//		    }			   
//			} else {
//
//			    $error[] = 'You have uploaded over ' . $convertMb . 'Mb';
//			}
			}
		    } else {
			$error[] = 'You have uploaded over ' . $convertMb . 'Mb';
		    }
		    if (!$error) {

			user()->getModel()->uploaded_size = $sizeUploadedOfUser + $totalSize;
			user()->getModel()->save();
			$model->attachment = serialize($attachment);
			$model->save();
			$attachment = unserialize($model->attachment);
		    } else {
			//when there was error
			//delete all file were uploaded
			if ($aNamePhoto) {
			    foreach ($aNamePhoto as $photo) {
				deleteFile(UPLOAD_PATH . 'photo/' . $photo);
			    }
			}
			if ($audio) {
			    deleteFile(UPLOAD_PATH . 'audio/' . $audio);
			}
			if ($video) {
			    deleteFile(UPLOAD_PATH . 'video/' . $video['upload']);
			}
		    }
		}
	    }
	} else {
	    $error[] = "You doesn't own this post."; //user is not possesive this post
	}


	$this->render('update', array('model' => $model, 'error' => $error, 'attachment' => $attachment));
    }

    private function _loadModel($id) {
	$model = Posts::model()->with('user')->findByPk($id);
	if ($model) {
	    return $model;
	} else {
	    throw new CHttpException(404, 'Page was not exists');
	}
    }

    public function actionSearch() {

	$model = new Posts;
	$critical = new CDbCriteria();

	$critical->with = array('user');

	if (isset($_POST['text-search']) && $_POST['text-search']) {
	    $critical->compare('t.title', $_POST['text-search'], true, 'OR');
	    $critical->compare('t.content', $_POST['text-search'], true, 'OR');
	    $critical->compare('user.display_name', $_POST['text-search'], true, 'OR');
	    $critical->compare('t.tags', $_POST['text-search'], true, 'OR');
	}

//	if (user()->id && user()->getModel()->status == User::STATUS_ACTIVE) {
//	    //get all friend 
//	    $aIdsFriend = Friend::getIdsFriend(user()->id);
//	    $sIdUser = user()->id;
//	    if ($aIdsFriend) {
//		foreach ($aIdsFriend as $id) {
//		    $sIdUser .= ',' . $id;
//		}
//	    }
//	    $critical->addCondition('t.user_id IN(' . $sIdUser . ') ');
//	}

	$critical->addCondition('t.is_private=' . Posts::IS_PUBLIC);

	$critical->order = 'post_id DESC';
	$iTotalRecord = $model->count($critical);

	$pages = new CPagination($iTotalRecord);
	$pages->pageSize = Posts::TOTAL_RECORD;
	$pages->applyLimit($critical);

	$this->render('search', array(
	    'model' => $model,
	    'aPosts' => $model->findAll($critical),
	    'pages' => $pages,
	    'iTotalRecord' => $iTotalRecord
	));
    }

    /**
     * delete image when edit post
     */
    public function actionDelete_file() {
	if (isset($_POST['fileName']) && isset($_POST['fileType']) && isset($_POST['postId'])) {
	    $model = Posts::model()->findByPk($_POST['postId']);
	    $aAttachment = unserialize($model->attachment);
	    switch ($_POST['fileType']) {
		case 'photo':
		    $key = array_search($_POST['fileName'], $aAttachment['photo']);
		    unset($aAttachment['photo'][$key]);
		    deleteFile(UPLOAD_PATH . 'photo/' . $_POST['fileName']);
		    break;
		case 'audio':
		    $aAttachment['audio'] = '';
		    deleteFile(UPLOAD_PATH . 'audio/' . $_POST['fileName']);
		    break;
		case 'video':
		    $aAttachment['video']['upload'] = '';
		    deleteFile(UPLOAD_PATH . 'video/' . $_POST['fileName']);
		    break;
	    }
	    $model->attachment = serialize($aAttachment);
	    $model->save();
	}
    }

    /**
     * Report abuse
     */
    public function actionReportAbuse() {
	if (isset($_POST['link']) && isset($_POST['userId']) && isset($_POST['itemId']) && isset($_POST['text']) && isset($_POST['type'])) {
	    $model = new Abuse();
	    $model->link_post = $_POST['link'];
	    $model->user_id = $_POST['userId'];
	    $model->item_id = $_POST['itemId'];
	    $model->type = $_POST['type'];
	    $model->message = $_POST['text'];
	    $model->time_created = time();
	    if ($model->save()) {
		echo 1;
	    }
	}
    }

}

